package com.why.zing.common.domain;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.why.zing.common.constant.ResultCode;
import com.why.zing.common.exception.ExceptionCode;
import com.why.zing.common.exception.ZingException;
import lombok.Data;

import java.io.Serializable;

/**
 * 通用返回result
 *
 * @author 睁眼看世界
 * @date 2019年7月30日
 */
@Data
public class ZingResult<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    private int code;
    private String info;
    private T data;

    private ZingResult() {
        this.code = ResultCode.SUCCESS.getCode();
        this.info = ResultCode.SUCCESS.getInfo();
    }

    private ZingResult(int code, String info) {
        this.code = code;
        this.info = info;
    }

    private ZingResult(T data) {
        this.code = ResultCode.SUCCESS.getCode();
        this.info = ResultCode.SUCCESS.getInfo();
        this.data = data;
    }

    private ZingResult(ExceptionCode exceptionCode) {
        this.code = exceptionCode.getCode();
        this.info = exceptionCode.getInfo();
    }

    public static ZingResult success() {
        return new ZingResult();
    }

    public static <T> ZingResult<T> success(T data) {
        return new ZingResult<>(data);
    }

    public static <T> ZingResult<T> error(ExceptionCode exceptionCode) {
        return new ZingResult<>(exceptionCode);
    }

    public static <T> ZingResult<T> error(ZingException exception) {
        return new ZingResult<>(exception.getCode(), exception.getInfo());
    }

    @JsonIgnore
    public Boolean isSuccess() {
        return this.code == ResultCode.SUCCESS.getCode();
    }


    @JsonIgnore
    public Boolean isDataSuccess() {
        return this.code == ResultCode.SUCCESS.getCode() && this.data != null;
    }
}
